package com.ivideo.backend.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ivideo.backend.mapper.SysRoleMapper;
import com.ivideo.backend.mapper.SysUserRoleMapper;
import com.ivideo.backend.model.system.SysRole;
import com.ivideo.backend.model.system.SysUserRole;
import com.ivideo.backend.model.vo.AssignRoleVo;
import com.ivideo.backend.service.SysRoleService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Project: ivideo-parent
 * @Name: SysRoleServiceImpl
 * @Author: Jack_Li
 * @Date: 2024/5/20 13:29
 */

@Service
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements SysRoleService {

    @Resource
    private SysUserRoleMapper sysUserRoleMapper;

    @Override
    public Map<String, Object> getRoleByUserId(Long userId)
    {
        // 获取所有角色
        List<SysRole> userRoles = this.list(null);
        // 根据用户 id 查询
        LambdaQueryWrapper<SysUserRole> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysUserRole::getUserId, userId);
        // 获取用户已分配的角色
        List<SysUserRole> sysUserRoles = sysUserRoleMapper.selectList(queryWrapper);
        // 获取用户已分配的角色 id
        List<Long> roleIds = new ArrayList<>();
        for (SysUserRole userRole : sysUserRoles) {
            roleIds.add(userRole.getRoleId());
        }
        // 封装数据
        Map<String, Object> map = new HashMap<>();
        map.put("allRoles", userRoles);
        map.put("userRoleIds", roleIds);
        return map;
    }

    @Override
    public void doAssign(AssignRoleVo assignRoleVo) {
        // 根据用户 id 删除原来分配的角色
        LambdaQueryWrapper<SysUserRole> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysUserRole::getUserId, assignRoleVo.getUserId());
        sysUserRoleMapper.delete(queryWrapper);
        // 获取角色 id 集合
        List<Long> roleIds = assignRoleVo.getRoleIdList();
        for (Long roleId : roleIds) {
            if(roleId != null) {
                SysUserRole sysUserRole = new SysUserRole();
                sysUserRole.setUserId(assignRoleVo.getUserId());
                sysUserRole.setRoleId(roleId);
                // 保存
                sysUserRoleMapper.insert(sysUserRole);
            }
        }
    }
}
